<?php

namespace app\kaoqin\api;

use app\common\logic\Department;
use app\common\logic\FullRecord;
use app\common\logic\RecordSumToday;
use app\common\logic\User;


class Dashboards extends Common
{
    /**
     * 今日最早到岗
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function earliest()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        if (!isset($req['time']) || empty($req['time'])) $time = time();
        else $time = strtotime($req['time']);

        $time_start = strtotime(date('Y-m-d 00:00:00', $time));
        $time_end = strtotime(date('Y-m-d 23:59:59', $time));

        $kq_hide_userid = c('kq_hide_userid');
        if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

        $where = ['unix_time' => ['between', [$time_start, $time_end]], 'userId' => ['not in', $kq_hide_userid]];

        $kq_show_all_userid = c('kq_show_all_userid');
        if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

        if (!in_array($uid, $kq_show_all_userid)) {
            $local_user = User::get(['userid' => $uid]);
            $dept_pid = Department::getPidById($local_user['department']);
            $child_id = Department::getChildIds($dept_pid);

            $where['depart_id'] = ['in', $child_id];
        }

        $ret = FullRecord::getEarliests($where);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }

    /**
     * 此刻在榜
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function onWorking()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $uid = getUid();

        $kq_hide_userid = c('kq_hide_userid');
        if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

        $where = ['count' => ['exp', '%2=1'], 'id' => ['not in', $kq_hide_userid]];

        $kq_show_all_userid = c('kq_show_all_userid');
        if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

        if (!in_array($uid, $kq_show_all_userid)) {
            $local_user = User::get(['userid' => $uid]);
            $dept_pid = Department::getPidById($local_user['department']);
            $child_id = Department::getChildIds($dept_pid);

            $where['pid'] = ['in', $child_id];
        }

        $ret = RecordSumToday::getOnWorking($where);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }

    /**
     * 昨日离岗
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function latest()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        if (!isset($req['time']) || empty($req['time'])) $time = strtotime("-1day");
        else $time = strtotime($req['time']);

        $time_start = strtotime(date('Y-m-d 00:00:00', $time));
        $time_end = strtotime(date('Y-m-d 23:59:59', $time));

        $kq_hide_userid = c('kq_hide_userid');
        if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

        $where = ['unix_time' => ['between', [$time_start, $time_end]], 'userId' => ['not in', $kq_hide_userid]];

        $kq_show_all_userid = c('kq_show_all_userid');
        if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

        if (!in_array($uid, $kq_show_all_userid)) {
            $local_user = User::get(['userid' => $uid]);
            $dept_pid = Department::getPidById($local_user['department']);
            $child_id = Department::getChildIds($dept_pid);

            $where['depart_id'] = ['in', $child_id];
        }

        $ret = FullRecord::getLatests($where);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }

    /**
     * 昨日打卡异常
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function exception()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        if (!isset($req['time']) || empty($req['time'])) $time = strtotime("-1day");
        else $time = strtotime($req['time']);

        $time_start = strtotime(date('Y-m-d 00:00:00', $time));
        $time_end = strtotime(date('Y-m-d 23:59:59', $time));

        $kq_hide_userid = c('kq_hide_userid');
        if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

        $where = ['unix_time' => ['between', [$time_start, $time_end]], 'userId' => ['not in', $kq_hide_userid]];

        $kq_show_all_userid = c('kq_show_all_userid');
        if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

        if (!in_array($uid, $kq_show_all_userid)) {
            $local_user = User::get(['userid' => $uid]);
            $dept_pid = Department::getPidById($local_user['department']);
            $child_id = Department::getChildIds($dept_pid);

            $where['depart_id'] = ['in', $child_id];
        }

        $ret = FullRecord::getExceptions($where);
        if ($ret === false)
            return $this->error('发生错误');
        return $this->success($ret);
    }

    /**
     * 返回首位附加状态的列表
     * @param $list
     * @return mixed
     * @author wb <pithyone@vip.qq.com>
     */
    private function addStatus($list)
    {
        $size = count($list);
        foreach ($list as $k => $v) {
            if (in_array($k, array(0, 1, 2))) {
                $list[$k]['status'] = 'first';
                $list[$k]['status_desc'] = '领先';
            } elseif (in_array($k, array($size - 3, $size - 2, $size - 1))) {
                $list[$k]['status'] = 'last';
                $list[$k]['status_desc'] = '落后';
            } else {
                $list[$k]['status'] = '';
                $list[$k]['status_desc'] = '';
            }
        }
        return $list;
    }

    /**
     * 前七天每天最晚离岗
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function lastleave()
    {
        if (!$this->checkAuth())
        return $this->_error;
        $req = input('');
        if (!isset($req['time']) || empty($req['time'])) $time = strtotime("-7day");            //-1day 昨天
        else $time = strtotime($req['time']);
        $time_start = $time;         //开始时间
        $time_end = strtotime("-1day");           //结束时间，昨天的最后

        $ret = FullRecord::getLastLeave($time_start, $time_end);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }

    /**
     *上周工时排序
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */

    public function gongshi_week()
    {
        if (!$this->checkAuth())
        return $this->_error;
        $uid = getUid();
        //是写死的
        $time["start_time"] = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));         //上周开始时间戳
        $time['end_time'] = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y"));         //上周结束时间戳
        $local_user = User::get(['userid' => $uid]);                        //返回登录用户的信息

        $dept_pid = Department::getPidById($local_user['department']);      //返回所属顶级部门的id
        $dept_id = Department::getChildIds($dept_pid);                        //返回所有部门的id

        $ret = FullRecord::SoftRecordByTime($time, $dept_id);
        if ($ret === false)
            return $this->error('发生错误');

        $rets = array();
        $tsum = 0;
        $retsIndex = 0;
        for ($j = 0; $j < count($ret); $j++) {
            $log = explode(",", $ret[$j]['log']);                                    //$rets[$i]['log']为打卡记录
            $count = count($log);
            if ($count % 2 == 0) {
                $tsum += intval($log[1]) - intval($log[0]);
            } else {
                $tsum += 0;
            }
            //如果还有下一条，说明不是最后一条数据。如果是最后一条判断最后一条跟上一条name一样不，如果不一样那就新增一条
            //如果还有下一条，如果当条跟下条name不一样，说明下条是新人。将当条记录好
            if ($j < count($ret) - 1) {
                if ($ret[$j]['userId'] != $ret[$j + 1]['userId']) {
                    $rets[$retsIndex]['name'] = $ret[$j]['name'];
                    $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                    $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                    $rets[$retsIndex]['tsum'] = $tsum;

                    $retsIndex++;
                    $tsum = 0;
                }
            } else if ($j == count($ret) - 1) {
                $rets[$retsIndex]['name'] = $ret[$j]['name'];
                $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                $rets[$retsIndex]['tsum'] = $tsum;
                $tsum = 0;
            }
        }
        array_multisort(array_column($rets, 'tsum'), SORT_DESC, $rets);          //二维数组排序
        for ($j = 0; $j < count($rets); $j++) {
            $tsum = FullRecord::change($rets[$j]['tsum']);
            $times = explode(":", $tsum);
            $time = $times[0] . "小时" . $times[1] . "分钟";
            $rets[$j]['tsum'] = $time;
        }
        return $this->success($rets);
    }

    /**
     *上月工时排序
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */

    public function gongshi_month()
    {
        if (!$this->checkAuth())
        return $this->_error;
        $uid = getUid();
        //是写死的
        $time["start_time"] = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));         //上月开始时间戳
        $time['end_time'] = mktime(23, 59, 59, date("m"), 0, date("Y"));         //上月结束时间戳
        $local_user = User::get(['userid' => $uid]);                        //返回登录用户的信息

        $dept_pid = Department::getPidById($local_user['department']);      //返回所属顶级部门的id
        $dept_id = Department::getChildIds($dept_pid);

        $ret = FullRecord::SoftRecordByTime($time, $dept_id);
        if ($ret === false)
            return $this->error('发生错误');

        $rets = array();
        $tsum = 0;
        $retsIndex = 0;
        for ($j = 0; $j < count($ret); $j++) {
            $log = explode(",", $ret[$j]['log']);                                    //$rets[$i]['log']为打卡记录
            $count = count($log);
            if ($count % 2 == 0) {
                $tsum += intval($log[1]) - intval($log[0]);
            } else {
                $tsum += 0;
            }
            //如果还有下一条，说明不是最后一条数据。如果是最后一条判断最后一条跟上一条name一样不，如果不一样那就新增一条
            //如果还有下一条，如果当条跟下条name不一样，说明下条是新人。将当条记录好
            if ($j < count($ret) - 1) {
                if ($ret[$j]['userId'] != $ret[$j + 1]['userId']) {
                    $rets[$retsIndex]['name'] = $ret[$j]['name'];
                    $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                    $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                    $rets[$retsIndex]['tsum'] = $tsum;

                    $retsIndex++;
                    $tsum = 0;
                }
            } else if ($j == count($ret) - 1) {
                $rets[$retsIndex]['name'] = $ret[$j]['name'];
                $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                $rets[$retsIndex]['tsum'] = $tsum;
                $tsum = 0;
            }
        }
        array_multisort(array_column($rets, 'tsum'), SORT_DESC, $rets);          //二维数组排序
        for ($j = 0; $j < count($rets); $j++) {
            $tsum = FullRecord::change($rets[$j]['tsum']);
            $times = explode(":", $tsum);
            $time = $times[0] . "小时" . $times[1] . "分钟";
            $rets[$j]['tsum'] = $time;
        }
        return $this->success($rets);
    }

    /* 迟到时间为早九点，迟到榜    一个月所有人迟到的次数
      @return array|string
      */
    public function late()
    {
        if (!$this->checkAuth())
        return $this->_error;
        $time["start_time"] = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));         //上月开始时间戳
        $time['end_time'] = mktime(23, 59, 59, date("m"), 0, date("Y"));         //上月结束时间戳

        $ret = FullRecord::late($time);
        if ($ret === false)
            return $this->error('发生错误');
        $rets = array();
        $retsIndex = 0;
        $time = strtotime("09:00:00");

        $count = 0;

        for ($j = 0; $j < count($ret); $j++) {
            $log = explode(",", $ret[$j]['log']);
            if (strtotime($log[0]) > $time) {
                $count += 1;
            }
            //如果还有下一条，说明不是最后一条数据。如果是最后一条判断最后一条跟上一条name一样不，如果不一样那就新增一条
            //如果还有下一条，如果当条跟下条name不一样，说明下条是新人。将当条记录好
            if ($j < count($ret) - 1) {
                if ($ret[$j]['userId'] != $ret[$j + 1]['userId']) {
                    $rets[$retsIndex]['name'] = $ret[$j]['name'];
                    $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                    $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                    $rets[$retsIndex]['late_count'] = $count;

                    $retsIndex++;
                    $count = 0;
                }
            } else if ($j == count($ret) - 1) {
                $rets[$retsIndex]['name'] = $ret[$j]['name'];
                $rets[$retsIndex]['avatar'] = $ret[$j]['avatar'];
                $rets[$retsIndex]['dept'] = $ret[$j]['dept'];
                $rets[$retsIndex]['late_count'] = $count;
                $count = 0;
            }
        }

        array_multisort(array_column($rets, 'late_count'), SORT_DESC, $rets);

        return $this->success($rets);
    }

    //查询上个月所有人补签成功次数统计
    //@return array|string
    public function buqian()
    {
        if (!$this->checkAuth())
        return $this->_error;
        $time["start_time"] = mktime(0, 0, 0, date("m") - 1, 1, date("Y"));         //上月开始时间戳
        $time['end_time'] = mktime(23, 59, 59, date("m"), 0, date("Y"));         //上月结束时间戳
        $ret = FullRecord::buqian($time);
        if ($ret === false)
            return $this->error('发生错误');

        return $this->success($ret);
    }
}